<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { ElTag } from 'element-plus'
import { Table } from '@/components/Table'
// import { getTableListApi, saveTableApi, delTableListApi } from '@/api/table'
import { useTable } from '@/hooks/web/useTable'
import { useSearch } from '@/hooks/web/useSearch'
import { ref, reactive } from 'vue'
import Write from './components/Write.vue'
// import Detail from './components/Detail.vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
// import { departmentMap } from '../../../../public/department'

import type { MissionInfo } from '@/api/bianmafuma/type'
//引入获取任务的请求的方法
import { downloadResult, reqAllMission, reqDepartmentMission } from '@/api/bianmafuma'
import { useRouter } from 'vue-router'
import { onMounted } from 'vue'
import { useUserStore } from '@/store/modules/user'

import { inject } from 'vue'

const  departmentMap  = inject<any>('departmentMap')

const userStore = useUserStore()

const $router = useRouter()

// const timer = ref<NodeJS.Timeout>()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    let res
    if (searchValue.value == 'all') res = await reqAllMission(currentPage.value, pageSize.value)
    else res = await reqDepartmentMission(searchValue.value, currentPage.value, pageSize.value)
    return {
      list: res.data.list,
      total: res.data.total
    }
  }
})
const { loading, dataList, total, currentPage, pageSize } = tableState
const { refresh } = tableMethods

const searchValue = ref('all')
searchValue.value = userStore.userInfo?.role === 'admin' ? 'all' : userStore.userInfo!.username

const { t } = useI18n()

const { searchRegister, searchMethods } = useSearch()
const { setValues } = searchMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    align: 'center',
    search: { hidden: true },
    form: { hidden: true }
  },
  {
    field: 'taskName',
    label: '任务名称',
    align: 'center',
    search: { hidden: true }
  },
  {
    field: 'applyTime',
    label: t('tableDemo.displayTime'),
    align: 'center',
    search: { hidden: true },
    form: {
      component: 'DatePicker',
      componentProps: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
    },
    table: {
      // 在表格中显示时间，确保时间格式正确
      formatter: (row: any) => {
        return row.applyTime ? new Date(row.applyTime).toLocaleString('zh-CN', { timeZone: 'UTC' }) : '-'
      }
    }
  },
  {
    field: 'finishTime',
    label: '结束时间',
    align: 'center',
    search: { hidden: true },
    form: {
      component: 'DatePicker',
      componentProps: { type: 'datetime', valueFormat: 'YYYY-MM-DD HH:mm:ss' }
    },
    table: {
      // 在表格中显示时间，确保时间格式正确
      formatter: (row: any) => {
        return row.finishTime ? new Date(row.finishTime).toLocaleString('zh-CN', { timeZone: 'UTC' }) : '-'
      }
    }
  },
  {
    field: 'taskDepartment',
    label: t('tableDemo.department'),
    align: 'center',
    search: {
      component: 'Select',
      componentProps: {
        options: [{ label: '所有部门', value: 'all' }].concat(
          Object.keys(departmentMap).map((key: string) => {
            return {
              label: departmentMap[key],
              value: key
            }
          })
        ),
        on: {
          change: (value: string) => {
            console.log(value)
            searchValue.value = value
            currentPage.value = 1
            refresh()
          }
        },
        clearable: false,
        disabled: userStore.userInfo?.role !== 'admin',
      },
    },
    table: {
      formatter: (row: any) => departmentMap[row.taskDepartment] || '-'
    }
  },
  {
    field: 'dataNum',
    label: t('tableDemo.encodingSize'),
    align: 'center',
    search: { hidden: true },
    table: {
      width: 100
    }
  },
  {
    field: 'taskStatus',
    label: t('tableDemo.encodingState'),
    align: 'center',
    formatter: (data: any) => {
      const state = taskState(data.taskStatus)
      return (
        <ElTag type={state.type as 'success' | 'danger' | 'warning' | 'info'}>{state.text}</ElTag>
      )
    },
    search: { hidden: true },
    table: {
      width: 100
    }
  },
  {
    field: 'action',
    width: '260px',
    label: t('tableDemo.action'),
    align: 'center',
    search: { hidden: true },
    form: { hidden: true },
    table: {
      fixed: 'right',
      width: '200',
      slots: {
        default: (data: any) => (
          <>
            <BaseButton type="primary" onClick={() => action(data.row)}>
              {t('exampleDemo.detail')}
            </BaseButton>
            <BaseButton
              type="success"
              disabled={data.row.taskStatus !== 1}
              onClick={() => download(data.row)}
            >
              {t('exampleDemo.download')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)
console.log(allSchemas)

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<MissionInfo | null>(null)
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = '编码赋码申请'
  currentRow.value = null
  dialogVisible.value = true
  actionType.value = ''
}

const download = (row: MissionInfo) => {
  downloadResult(row.id as string).then((res) => {
    const excel = res
    const downloadUrl = window.URL.createObjectURL(
      new Blob([excel!], { type: 'application/vnd.ms-excel' })
    )
    // if (downloadUrl.includes('http:')) {
    //     downloadUrl = downloadUrl.replace('http:', 'https:');
    // }
    const a = document.createElement('a')
    a.style.display = 'none'
    a.href = downloadUrl
    a.download = '编码赋码结果.xlsx'
    const event = new MouseEvent('click')
    a.dispatchEvent(event)
  })
}

const taskState = (state: number) => {
  switch (state) {
    case 0:
      return {
        text: '进行中',
        type: 'primary'
      }
      break
    case 1:
      return {
        text: '已完成',
        type: 'success'
      }
      break
    case 2:
      return {
        text: '错误',
        type: 'danger'
      }
    default:
      return {
        text: '进行中',
        type: 'primary'
      }
  }
}

const action = (row: MissionInfo) => {
  $router.push({
    path: '/encoding/application-detail',
    query: {
      id: row.id
    }
  })
}

const writeRef = ref<ComponentRef<typeof Write>>()

const upload = () => {
  writeRef.value!.submitUpload()
}

const closeDialog = () => {
  dialogVisible.value = false
  setTimeout(() => {
    refresh()
  }, 3000)
}

const resetSearch = () => {
  searchValue.value = 'all'
  setValues({ taskDepartment: searchValue.value })
  currentPage.value = 1
  refresh()
}

onMounted(() => {
  setValues({
    taskDepartment: searchValue.value
  })
})
</script>

<template>
  <ContentWrap>
    <div style="display: flex; justify-content: space-between">
      <Search :schema="allSchemas.searchSchema" :show-search="false" :show-reset="userStore.userInfo?.role=='admin'" @register="searchRegister" @reset="resetSearch" />
      <BaseButton type="primary" @click="AddAction">申请上传</BaseButton>
    </div>

    <Table v-model:pageSize="pageSize" v-model:currentPage="currentPage" :columns="allSchemas.tableColumns"
      headerAlign="center" :data="dataList" :loading="loading" :pagination="{
        total: total
      }" @register="tableRegister" />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" width="800" maxHeight="550px">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :departments="departmentMap" @close-dialog="closeDialog" />

    <!-- <Detail v-if="actionType === 'detail'" :current-row="currentRow" /> -->

    <template #footer>
      <BaseButton v-if="actionType !== 'detail'" type="primary" @click="upload">
        确认申请
      </BaseButton>
      <BaseButton @click="closeDialog">{{ actionType !== 'detail' ? '取消' : '返回' }}</BaseButton>
    </template>
  </Dialog>
</template>
../department
